<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/12/10
 * Time: 17:11
 */
namespace app\common\widget\weixin;

use app\common\config\weixin_config;
use app\common\helper\appmenu_helper;
use app\common\helper\company_helper;
use app\common\helper\material_helper;
use app\common\helper\open_card_helper;
use app\common\helper\setting_helper;
use app\common\helper\weixin_helper;

class mass_widget
{
    private $company_id;
    private $open_card_id;
    private $appmenu_key = array();
    private $appid;
    private $appsecret;
    private $access_token;

    public function __construct()
    {
        $this->open_card_id   = open_card_helper::get_open_card_id();
        $this->company_id     = company_helper::get_company_id();

        $appmenu_key = setting_helper::get_setting_info('appmenu_key');
        if ($appmenu_key) {
            $this->appmenu_key = unserialize($appmenu_key);

            $this->appid        = $this->appmenu_key['appid'];
            $this->appsecret    = $this->appmenu_key['appsecret'];
            $this->access_token = $this->appmenu_key['access_token'];
        }
        //var_dump($this->open_card_id,$this->company_id,$appmenu_key,222);

    }

    /**
     * 根据标签进行群发
     * @param string $media_id
     * @return mixed
     */
    public function mass_sendall($params)
    {
        /**
         * 返回数据示例
         * {
        "errcode":0,
        "errmsg":"send job submission success",
        "msg_id":34182,
        "msg_data_id": 206227730
        }
         */

        $send_data = array(
            'filter'    => array(
                'is_to_all' => false,
                'tag_id'    => 0
            )
        );

        // 拼装发送的目标（全体/指定标签）
        if (isset($params['is_to_all']) && $params['is_to_all'] == 1) {
            $send_data['filter']['is_to_all'] = true;
            $send_data['filter']['tag_id'] = 0;

        } else {
            if (!isset($params['tag_id']) || !$params['tag_id']) {
                return '请传递要发送的方式，按标签发送/还是群发所有人';
            }

            $send_data['filter']['is_to_all'] = false;
            $send_data['filter']['tag_id'] = $params['tag_id'];
        }

        if (!isset($params['media_type']) || !$params['media_type']) {
            return '请传递要发送的消息类型';
        }
        if ((!isset($params['media_id']) || !$params['media_id'])
            && (!isset($params['content']) || !$params['content'])) {
            return '请传递要发送的消息media_id或内容';
        }

        if ($params['media_type'] == 'news') {
            $params['media_type'] = 'mpnews';
        }

        // 拼装发送的消息
        if ($params['media_type'] == 'text') {
            $send_data[$params['media_type']] = array(
                'content' => weixin_helper::fix_weixin_content($params['content'])
            );

        } else {
            $send_data[$params['media_type']] = array(
                'media_id' => $params['media_id']
            );
        }

        // 拼装发送的类型
        $send_data['msgtype'] = $params['media_type'];

        //an_dump($send_data);//exit;
        $data = decode_unicode(json_encode($send_data));
        $url = str_replace(array('{ACCESS_TOKEN}'), array($this->access_token), weixin_config::$mass_sendall_url);
        $res = h_curl($url, $data, 1);
        if (isset($res['errcode']) && $res['errcode'] != 0) {
            // 如果accesss_token失效，重新发送一次
            if (in_array($res['errcode'], array('42001', '40001', '41001'))) {
                $check_flag = $this->check_app_params();
                if ($check_flag) {
                    return $check_flag;
                }

                $url = str_replace(array('{ACCESS_TOKEN}'), array($this->access_token), weixin_config::$mass_sendall_url);
                $res = h_curl($url, $data, 1);
            }
        }

        //an_dump($res);
        if (isset($res['errcode']) && $res['errcode'] != 0) {
            if (array_key_exists($res['errcode'], weixin_config::$err_code)) {
                return weixin_config::$err_code[$res['errcode']].' '.$res['errcode'].' file'.__FUNCTION__.__LINE__;
            }

            // 如果接口调用达到上限，清除接口调用次数
            if ($res['errcode'] == 45009) {
                $clear_result =(new weixin_widget())->clear_quota();
                if ($clear_result != 'ok') {
                    return $clear_result;
                }

                return (new mass_widget())->mass_sendall($params);
            }

            return '回复失败 '.$res['errcode'];
        }

        return array('info'=>'ok', 'res'=>$res);
    }

    /**
     * 根据OpenID列表群发
     * @param array $openids_arr 发送的目标
     * @param array 消息类型、数据等
     * @return mixed
     */
    public function mass_send($openids_arr, $params)
    {
        /**
         * 返回数据示例
         * {
        "errcode":0,
        "errmsg":"send job submission success",
        "msg_id":34182,
        "msg_data_id": 206227730
        }
         */

        if (!$openids_arr) {
            return '请传递要群发给哪些人';
        }

        // 如果只有一个open_id，拼成两个
        if (count($openids_arr) == 1) {
            $openids_arr[1] = $openids_arr[0];
        }

        $send_data = array(
            'touser'    => $openids_arr
        );

        if (!isset($params['media_type']) || !$params['media_type']) {
            return '请传递要发送的消息类型';
        }
        if ((!isset($params['media_id']) || !$params['media_id'])
            && (!isset($params['content']) || !$params['content'])) {
            return '请传递要发送的消息media_id或内容';
        }

        if ($params['media_type'] == 'news') {
            $params['media_type'] = 'mpnews';
        }

        // 拼装发送的消息
        if ($params['media_type'] == 'text') {
            $send_data[$params['media_type']] = array(
                'content' => weixin_helper::fix_weixin_content($params['content'])
            );

        } else {
            $send_data[$params['media_type']] = array(
                'media_id' => $params['media_id']
            );
        }

        // 拼装发送的类型
        $send_data['msgtype'] = $params['media_type'];

        //an_dump($send_data);
        $data = decode_unicode(json_encode($send_data));
        $url = str_replace(array('{ACCESS_TOKEN}'), array($this->access_token), weixin_config::$mass_send_url);
        $res = h_curl($url, $data, 1);
        if (isset($res['errcode']) && $res['errcode'] != 0) {
            // 如果accesss_token失效，重新发送一次
            if (in_array($res['errcode'], array('42001', '40001', '41001'))) {
                $check_flag = $this->check_app_params();
                if ($check_flag) {
                    return $check_flag;
                }

                $url = str_replace(array('{ACCESS_TOKEN}'), array($this->access_token), weixin_config::$mass_send_url);
                $res = h_curl($url, $data, 1);
            }
        }

        //an_dump($res);
        if (isset($res['errcode']) && $res['errcode'] != 0) {
            if (array_key_exists($res['errcode'], weixin_config::$err_code)) {
                return weixin_config::$err_code[$res['errcode']].' '.$res['errcode'];
            }

            return '回复失败 '.$res['errcode'].' '.$res['errmsg'];
        }

        return array('info'=>'ok', 'res'=>$res);
    }


    /**
     * 群发消息
     * @param string $media_id
     * @return mixed
     */
    public function mass_send_check($wx_msg_id)
    {
        /**
         * 返回数据示例
         * {
        "msg_id":201053012,
        "msg_status":"SEND_SUCCESS"
        }
         */

        $data = array(
            'msg_id'    => $wx_msg_id
        );

        $data = decode_unicode(json_encode($data));
        $url = str_replace(array('{ACCESS_TOKEN}'), array($this->access_token), weixin_config::$masss_send_check_url);
        $res = h_curl($url, $data, 1);
        if (isset($res['errcode']) && $res['errcode'] != 0) {
            // 如果accesss_token失效，重新发送一次
            if (in_array($res['errcode'], array('42001', '40001', '41001'))) {
                $check_flag = $this->check_app_params();
                if ($check_flag) {
                    return $check_flag;
                }

                $url = str_replace(array('{ACCESS_TOKEN}'), array($this->access_token), weixin_config::$masss_send_check_url);
                $res = h_curl($url, $data, 1);
            }
        }

        //an_dump($res);
        if (isset($res['errcode']) && $res['errcode'] != 0) {
            if (array_key_exists($res['errcode'], weixin_config::$err_code)) {
                return weixin_config::$err_code[$res['errcode']].' '.$res['errcode'];
            }

            return '请求失败 '.$res['errcode'];
        }

        return array('info'=>'ok', 'res'=>$res);
    }

    /**
     * 检查并更新appid appsecret accesstoken
     * @return string
     */
    private function check_app_params()
    {
        $access_token = appmenu_helper::get_access_token_new($this->appid, $this->appsecret);
        if (!$access_token) {
            return '获取凭证失败，请检查授权信息';
        }

        $this->appmenu_key['access_token'] = $access_token;
        $this->access_token = $access_token;
        setting_helper::update_setting_info('appmenu_key', serialize($this->appmenu_key));

        return '';
    }
}